import React, { useEffect } from 'react';
import { Modal, Form, Input, Select, InputNumber, DatePicker } from 'antd';
import { FormItemConfig } from '../types/form';

const { TextArea } = Input;
const { Option } = Select;

interface CommonFormModalProps<T = Record<string, unknown>> {
  /** 弹窗是否可见 */
  visible: boolean;
  /** 弹窗标题 */
  title: string;
  /** 是否为添加模式 */
  isAddMode: boolean;
  /** 当前编辑的数据 */
  currentRecord?: T | null;
  /** 表单配置项 */
  formItems: FormItemConfig[];
  /** 表单初始值 */
  initialValues?: Partial<T>;
  /** 弹窗宽度 */
  width?: number;
  /** 提交回调 */
  onSubmit: (values: T, isAddMode: boolean, currentRecord?: T | null) => Promise<void> | void;
  /** 取消回调 */
  onCancel: () => void;
  /** 表单验证失败回调 */
  onValidateFailed?: (errorInfo: unknown) => void;
  /** 是否在提交时显示loading */
  loading?: boolean;
  /** 是否销毁弹窗内容 */
  destroyOnHidden?: boolean;
  /** 是否点击遮罩关闭 */
  maskClosable?: boolean;
}

/**
 * 通用表单弹窗组件
 * 支持添加和编辑模式，自动处理表单状态管理
 */
function CommonFormModal<T = Record<string, unknown>>({
  visible,
  title,
  isAddMode,
  currentRecord,
  formItems,
  initialValues,
  width = 600,
  onSubmit,
  onCancel,
  onValidateFailed,
  loading = false,
  destroyOnHidden = true,
  maskClosable = false,
}: CommonFormModalProps<T>) {
  const [form] = Form.useForm();

  // 当弹窗打开时，根据模式设置表单值
  useEffect(() => {
    if (visible) {
      if (isAddMode) {
        // 添加模式：使用初始值或空值
        form.setFieldsValue(initialValues || {});
      } else {
        // 编辑模式：使用当前记录的值
        form.setFieldsValue(currentRecord || {});
      }
    } else {
      // 弹窗关闭时重置表单
      form.resetFields();
    }
  }, [visible, isAddMode, currentRecord, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      await onSubmit(values, isAddMode, currentRecord);
      form.resetFields();
    } catch (errorInfo) {
      console.error('表单验证失败:', errorInfo);
      onValidateFailed?.(errorInfo);
    }
  };

  // 处理取消操作
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  // 渲染表单项
  const renderFormItem = (item: FormItemConfig) => {
    const { name, label, type, rules, placeholder, options, disabled, ...restProps } = item;

    // 根据类型渲染不同的表单项
    switch (type) {
      case 'input':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <Input
              placeholder={placeholder}
              disabled={disabled}
            />
          </Form.Item>
        );
      
      case 'textarea':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <TextArea
              placeholder={placeholder}
              rows={4}
              disabled={disabled}
            />
          </Form.Item>
        );
      
      case 'select':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <Select
              placeholder={placeholder}
              disabled={disabled}
              allowClear
            >
              {options?.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        );
      
      case 'number':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <InputNumber
              placeholder={placeholder}
              disabled={disabled}
              style={{ width: '100%' }}
              min={0}
              precision={0}
            />
          </Form.Item>
        );
      
      case 'password':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <Input.Password
              placeholder={placeholder}
              disabled={disabled}
            />
          </Form.Item>
        );
      
      case 'email':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <Input
              type="email"
              placeholder={placeholder}
              disabled={disabled}
            />
          </Form.Item>
        );
      
      case 'date':
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <DatePicker
              placeholder={placeholder}
              disabled={disabled}
              style={{ width: '100%' }}
            />
          </Form.Item>
        );
      
      default:
        return (
          <Form.Item
            key={name}
            name={name}
            label={label}
            rules={rules}
            {...restProps}
          >
            <Input
              placeholder={placeholder}
              disabled={disabled}
            />
          </Form.Item>
        );
    }
  };

  return (
    <Modal
      title={title}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
      width={width}
      confirmLoading={loading}
      destroyOnHidden={destroyOnHidden}
      maskClosable={maskClosable}
    >
      <Form
        form={form}
        layout="vertical"
        preserve={false}
      >
        {formItems.map(renderFormItem)}
      </Form>
    </Modal>
  );
}

export default CommonFormModal;
